/**   
 * @Title: DESUtil.java
 * @Package com.nbst.comnutil
 * @Description:
 * @author King  
 * @date 2018-9-29  
 */

package com.nbst.comnutil;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: DESUtil
 * @Description:DES算法加密解密
 * @author King
 * @date 2018-9-29
 * 
 */

public class DESUtil {

	private static final byte[] DES_KEY = { 27, 11, -100, 88, -34, -89, -128,
			-61 };
	
	private static final Logger logger = LoggerFactory.getLogger(DESUtil.class);

	/**
	 * 数据加密，算法（DES）
	 * 
	 * @param data
	 *            要进行加密的数据
	 * @return 加密后的数据
	 */
	public static String encrypt(String data) {
		if(StringUtil.isEmpty(data)) {
			data = "";
		}
		String encryptedData = null;
		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			DESKeySpec deskey = new DESKeySpec(DES_KEY);
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(deskey);
			// 加密对象
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key, sr);
			// 加密，并把字节数组编码成字符串
			encryptedData = new Base64().encodeToString(cipher.doFinal(data
					.getBytes()));
		} catch (Exception e) {
			logger.error("加密错误，错误信息：", e);
		}
		return encryptedData;
	}

	/**
	 * 数据解密，算法（DES）
	 * 
	 * @param cryptData
	 *            加密数据
	 * 
	 * @return 解密后的数据
	 */
	public static String decrypt(String cryptData) {
		String decryptedData = null;
		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			DESKeySpec deskey = new DESKeySpec(DES_KEY);
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(deskey);
			// 解密对象
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key, sr);
			// 把字符串解码为字节数组，并解密
			decryptedData = new String(cipher.doFinal(new Base64()
					.decode(cryptData)));
		} catch (Exception e) {
			logger.error("解密错误，错误信息：", e);
		}
		return decryptedData;
	}

}
